/**
 * Created with Vim7.3 ubuntu12.04
 * @fileOverview : 
 * @author : Lyle <lylechen2014@gmial.com>
 * @since : 2014-11-26 11:59:15
 * @filename : controller/gold_monitor.js
 * @version : 
 * @description : 
 */

define(function(require, exports, module){

    var name = 'Gold Monitor', mId = 'gold_monitor',
        highchartMC = require('{model}highchart'), 
        tpl = require('{view}gold_monitor.tpl'),
        tplT = require('{view}table.tpl'),
        highcharts = require('highcharts');
        

    var highchartM = new highchartMC.highchartM;

    var GoldMonitorView = Backbone.View.extend({

        initialize: function (obj) { 
            this.run(obj);
            this.bindEvt();
        },
  
        tplRender : function() {
            if ($('#'+mId).length < 1) { 
                $('#index_right').append(_.template(tpl)({obj:{name:name,mId:mId}}));
                this.fetchData(0); 
            } else {
                $('#'+mId).css('display','block');
            } 
        },

        bindEvt : function() {
            var tthis = this , dom = $('#'+mId);
            $("body").delegate('.refresh_graph','click.gold_monitor',function(){
                tthis.fetchData(1); 
            })
        },

        run : function(obj) {
            if ($('.main').length !== 3) { 
                Backbone.routerObj.navigate('index/w/'+mId, { trigger: true });return;
            } else {
                this.tplRender();
            }
        },

        fetchData : function(f) {
            var tthis = this,
                ajaxOpt = {
                url : seajs.data.vars.apiUrl+'realtime_gold_monitor',
                type : 'POST',
                data : { force_refresh: f },
                success : function(data) {
                    var siteInfo = share.getLocalStorage("siteInfo");
                    _.each(data,function(value,key){
                           if (_.isObject(value)) {
                               if (key == 'all') {
                                   value.site = 'All Sites';
                               } else {
                                   //console.log(value.engine_id,siteInfo[value.engine_id]);
                                   value.site = typeof(siteInfo[value.engine_id]) !== 'undefined' ? siteInfo[value.engine_id].name : undefined ;
                               }
                           }
                    });
                    tthis.fetchSuccess(data);
                },
                error : function(xhr, errorType, error) {
                },
                complete : function(xhr,status){
                    share.load($('#'+mId),false); 
                }
            };
           
            share.load($('#'+mId),true); 
            share.ajax(ajaxOpt);
        },
     
        fetchSuccess : function(data) {
            var arr = [];
                arr.push(data['all']);
                arr.push(data[7]);
                arr.push(data[21]);

            $('#'+mId).find('.check_time').html(data.time_seg);

            var tpl_gmra = require('{view}gold_monitor_ratio_area.tpl');
            $('#'+mId).find('.ratio_area_box').html(_.template(tpl_gmra)({arr:arr}));

            this.details(arr);
            this.changeHighChartM(arr);  
        },
 
        details : function(data) {
            
            var arr = [];
                arr.push({name:'Site',val:'site', title:'Site'});
                arr.push({name:'Ratio',val:'ratio',unit:'%', title:'Current Gold / History Gold'});
                arr.push({name:'History Gold',val:'avg',title:'Average gold of past'});
                arr.push({name:'Now Gold',val:'cnt_today',title:'Today\'s new gold till this moment'});
      
            $('#'+mId).find('.table').html(_.template(tplT)({obj:data,arr:arr}));

        },
 
        changeHighChartM : function(arr) {

            var xAxis = highchartM.get('xAxis'),
                yAxis = highchartM.get('yAxis'),
                tooltip = highchartM.get('tooltip');
                series = highchartM.get('series'),
                plotOptions = highchartM.get('plotOptions'),
                chart = highchartM.get('chart'),
                title = highchartM.get('title');

                title = {text : ''};
                chart = {type : 'column',width:$('#index_right').width()}; 
                xAxis = {categories : _.pluck(arr,'site')}; 
                yAxis = {
                    title: {
                        text: 'Number'
                    }
                };
                tooltip = {};
                series =  [
                    {
                        name: 'History Gold', 
                        color: '#5B9BD5',
                        data: _.map(_.pluck(arr,'avg'),function(num){return parseInt(num)}),
                        dataLabels: {
                            enabled: true,
                        }
                    },
                    {
                        name: 'Current Gold',
                        color: '#ED7D31',
                        data: _.map(_.pluck(arr,'cnt_today'),function(num){return parseInt(num)}),
                        dataLabels: {
                            enabled: true,
                        }
                    }
                ];

                plotOptions = {
                        column :  {
                            pointPadding: 0.2,
                            borderWidth: 0
                        }
                };
 
                highchartM.set('tooltip',tooltip);
                highchartM.set('title',title); 
                highchartM.set('plotOptions',plotOptions); 
                highchartM.set('xAxis',xAxis); 
                highchartM.set('yAxis',yAxis); 
                highchartM.set('series',series);
                highchartM.set('chart',chart);
 
                this.renderHighChart();     
        }, 

        renderHighChart : function() {
             $('#'+mId+'_graph').highcharts(highchartM.attributes);
        }

    });
 
	module.exports = GoldMonitorView;
});

